﻿using System;
using System.Collections;
using UnityEngine;

#if UNITY_EDITOR
#endif

namespace Share
{
    public class ResourceLoader : SingletonMonoObject<ResourceLoader>
    {



        public T[] LoadAll<T>(string path) where T : UnityEngine.Object
        {
            return Resources.LoadAll<T>(path);
        }
        public T LoadAsset<T>(string path, bool dontDestory = false) where T : UnityEngine.Object
        {
            //#if UNITY_EDITOR
            //收集 加载 资源
            // ResourceLoaderViewerData.Instance.AddLoaderPath(path);
            //#endif
            return Resources.Load<T>(path);

        }

        /// <summary>
        /// 异步加载资源
        /// </summary>
        /// <typeparam name="T">资源类型</typeparam>
        /// <param name="path">资源路径</param>
        /// <param name="_callBack">加载完成回调</param>
        /// <param name="_dontDestory">是否不销毁</param>
        public void LoadAssetAsync<T>(string path, Action<T> _callBack, bool _dontDestory = false) where T : UnityEngine.Object
        {
            StartCoroutine(LoadAssetAsyncCoroutine(path, _callBack, _dontDestory));
        }

        private IEnumerator LoadAssetAsyncCoroutine<T>(string path, Action<T> callback, bool dontDestroy) where T : UnityEngine.Object
        {
            ResourceRequest request = Resources.LoadAsync<T>(path);
            yield return request;

            if (request.asset == null)
            {
                Debug.LogError($"Failed to load asset at path: {path}");
                callback?.Invoke(null);
                yield break;
            }

            T asset = request.asset as T;
            if (asset == null)
            {
                Debug.LogError($"Asset type mismatch at path: {path}");
                callback?.Invoke(null);
                yield break;
            }

            if (dontDestroy)
            {
                DontDestroyOnLoad(asset);
            }

            callback?.Invoke(asset);
        }


    }
}
